const { adduser, finduser, userupdate } = require('../service/login')
const jwt = require('jsonwebtoken')
const axios = require('axios')
const SMSClient = require('@alicloud/sms-sdk');
const bcrypt = require('bcryptjs');
let phonenmber = []
module.exports = {
    async pdphoneyzm(ctx, next) {
        const { phone, code } = ctx.request.body
        const data = phonenmber.find(e => e.phone == phone)
        if (data && data.code == code) {
            phonenmber = phonenmber.filter(e => e.phone != phone)
            const rudata = await finduser({ phone })
            if (rudata) {
                const { password, ...alldata } = rudata.dataValues
                return ctx.body = {
                    code: 200,
                    data: {
                        ...alldata,
                    },
                    token: jwt.sign(alldata, 'ximo', { expiresIn: '5h' })
                }
            }
            return ctx.body = {
                code: 100,
                data: {
                    msg: '输入创建密码！'
                }
            }
        }
        return ctx.body = {
            code: 0,
            data: {
                msg: '验证码错误'
            }
        }
    },
    async wxlogin(ctx, next) {
        const { nickName: name, gender, language, province, avatarUrl: img, code } = ctx.request.body
        const { data } = await axios.get("https://api.weixin.qq.com/sns/jscode2session", { params: { appid: "wxd26211abc141c3b2", secret: "8b4e5caf70e4db58840a67c0cab6746d", js_code: code, grant_type: "authorization_code" } })
        const rudata = await finduser({ openid: data.openid })
        if (rudata) {
            const { openid, ...alldata } = rudata.dataValues
            ctx.body = {
                code: 200,
                data: {
                    ...alldata,

                }, token: jwt.sign(alldata, 'ximo', { expiresIn: '5h' })
            }
        } else {
            const addrudata = await adduser({ name, img, openid: data.openid })
            const { openid, ...alldata } = await finduser({ openid: data.openid }).dataValues
            ctx.body = {
                code: 200,
                data: {
                    ...alldata,

                },
                token: jwt.sign(alldata, 'ximo', { expiresIn: '5h' })
            }
        }
    },
    async sendphoneyzm(ctx, next) {
        // 设置值
        let accessKeyId = "LTAI5tEeLSHic6ADLHMw2wzk";// AccessKey ID
        let secretAccessKey = "9pNGfp8d6mo1KHYIPVsjKWFUNG754a";// AccessKey Secret
        let signName = "兮沒短信"; // 签名名称
        let templateCode = "SMS_475215311";// 短信模板code

        // 初始化sms_client
        const smsClient = new SMSClient({ accessKeyId, secretAccessKey })

        let phoneNum = ctx.query.phone;//手机号
        // 生成六位随机验证码
        let smsCode = Math.random().toString().slice(-6);
        console.log("smsCode:", smsCode);

        // 开始发送短信
        try {
            const result = await smsClient.sendSMS({
                PhoneNumbers: phoneNum,
                SignName: signName, //签名名称 前面提到要准备的
                TemplateCode: templateCode, //模版CODE  前面提到要准备的
                // TemplateParam: `{"code":'${str}'}`, // 短信模板变量对应的实际值，JSON格式
                TemplateParam: `{"code":'${smsCode}'}`, // 短信模板变量对应的实际值，JSON格式
            })

            let { Code } = result;
            if (Code == 'OK') {
                const id = phonenmber.find(e => e.phone == phoneNum)
                if (id) {
                    id.code = smsCode
                } else {
                    phonenmber.push({ phone: phoneNum, code: smsCode })
                }
                ctx.body = {
                    code: 200,
                    msg: 'success',
                }
            }
        } catch (error) {
            console.log("报错：", error);
            ctx.body = {
                code: 1,
                msg: 'fail: ' + error
            }
        }

    },
    async adduser(ctx, next) {
        const { phone, password } = ctx.request.body
        const salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt);
        const rudata = await adduser({ phone, password: hash })
        if (rudata) {
            const { password, ...alldata } = rudata.dataValues
            ctx.body = {
                code: 200,
                data: {
                    ...alldata
                },
                token: jwt.sign(alldata, 'ximo', { expiresIn: '5h' })
            }
        } else {
            ctx.body = {
                code: 0,
                data: {
                    msg: '注册失败'
                }
            }
        }
    },
    async phonelogin(ctx, next) {
        const { phone, password } = ctx.query
        const rudata = await finduser({ phone })
        if (!rudata) {
            return ctx.body = {
                code: 0,
                msg: '用户不存在'
            }
        }
        const { password: hash, ...alldata } = rudata.dataValues
        const isMatch = bcrypt.compareSync(password, hash);
        if (isMatch) {
            return ctx.body = {
                code: 200,
                data: alldata,
                token: jwt.sign(alldata, 'ximo', { expiresIn: '5h' })
            }
        }
        return ctx.body = {
            code: 401,
            msg: '账号或密码错误！'
        }
    },
    async ishasphone(ctx, next) {
        const { phone } = ctx.query
        const rudata = await finduser({ phone })
        if (!rudata) {
            return ctx.body = {
                code: 0,
                msg: "手机号未注册！"
            }
        }
        return ctx.body = {
            code: 200,
            msg: "手机号已注册！"
        }
    },
    async updatepassword(ctx, next) {
        const { phone, password } = ctx.request.body
        const salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt);
        const rudata = await userupdate({ phone }, { password: hash })
        console.log(rudata)
        ctx.body = {
            code: 200,
            msg: '修改成功'
        }
    }
}